package com.glela.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.glela.platform.model.*;
import com.glela.platform.model.request.*;
import org.apache.cxf.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.glela.api.im.rongcloud.ApiHttpClient;
import com.glela.api.im.rongcloud.vo.SdkHttpResult;
import com.glela.api.upload.qiniu.general.QiniuUtils;
import com.glela.api.upload.qiniu.impl.UploadObject;
import com.glela.api.upload.util.ImageProperties;
import com.glela.common.ImgBasePathRequest;
import com.glela.common.annotation.IpAccessAnnotation;
import com.glela.common.beans.FormatType;
import com.glela.common.constant.BaseRestrictionsEnum;
import com.glela.common.constant.CFlagEnum;
import com.glela.common.constant.ClientType;
import com.glela.common.constant.CommonConstants;
import com.glela.common.exception.BusinessException;
import com.glela.common.exception.InvalidArgumentException;
import com.glela.common.exception.PlatformException;
import com.glela.common.util.Base64;
import com.glela.common.util.DateUtil;
import com.glela.common.util.DateUtils;
import com.glela.common.util.IPUtils;
import com.glela.common.util.StringUtil;
import com.glela.constant.SmsConstant;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.response.MemberFeeAndTotalSale;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.model.response.ResponseMineInfoModel;
import com.glela.platform.model.response.ResponseNewUserModel;
import com.glela.platform.model.response.ResponsePageModel;
import com.glela.platform.model.response.ResponsePersonalInfoset;
import com.glela.platform.model.response.ResponseResultModel;
import com.glela.platform.model.response.ResponseTeacher;
import com.glela.platform.model.response.ResponseUser;
import com.glela.platform.model.response.ResponseUserPage;
import com.glela.platform.model.response.ResponseUserVo;
import com.glela.platform.model.response.UserInitResponse;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.platform.service.CheckCodeService;
import com.glela.platform.service.IChannelService;
import com.glela.platform.service.IGuestService;
import com.glela.platform.service.SmsService;
import com.glela.platform.service.TokenService;
import com.glela.platform.service.UnifiedTreatmentService;
import com.glela.platform.service.UserAdviceService;
import com.glela.platform.service.UserIdCardService;
import com.glela.platform.service.UserPayInfoService;
import com.glela.platform.service.UserService;
import com.glela.platform.service.UserSetService;
import com.glela.platform.util.ParameterUtils;
import com.glela.platform.vo.UserBasicInfo;
import com.glela.platform.vo.UserSwitchInfo;

@Controller
@RequestMapping(value = "/user")
public class UserController {
	private static Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;
	@Autowired
	private TokenService tokenService;
	@Autowired
	private SmsService smsService;
	@Autowired
	private IChannelService channelService;
	@Autowired
	private IGuestService guestService;
	@Resource
	private UserSetService userSetService;
	@Resource
	private UserAdviceService userAdviceService;
	@Resource
	private CheckCodeService checkCodeService;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	@Autowired
	private UnifiedTreatmentService unifiedTreatmentService;
	@Autowired
	private UserIdCardService userIdCardService;
	
	@Autowired
	private  UserPayInfoService userPayInfoService;
	
	
	
	

	private ResponseEntity<?> checkUser(ResponseUser user,String clientType) {
		Long userId = user.getUserId();
		if (1 == user.getLockStatus()) {
			userService.logOut(userId,clientType);// 删除token
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20103), HttpStatus.OK);
		} else if (1 == user.getIsBlack()) {
			userService.logOut(userId,clientType);// 删除token
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20119), HttpStatus.OK);
		} else {
			return null;
		}
	}

	private void setUserToken(ResponseUser user,String clientType) throws Exception {
		user.setToken(tokenService.SaveToken(user,clientType));
		user.setPicture(user.getPicture());
		SdkHttpResult sdkHttpResult;
		BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache("RONG_CLOUD_CREATE_TOKEN");
		if (null != baseRestrictions) {
			if (baseRestrictions.getStatus().toString().equals("0")) {//禁用
				sdkHttpResult = new SdkHttpResult(200, "");//返回空字符串
			} else {
				sdkHttpResult = ApiHttpClient.getToken(String.valueOf(user.getUserId()), user.getUserName(),
						user.getPicture(), FormatType.json);
			}
		} else {
			sdkHttpResult = ApiHttpClient.getToken(String.valueOf(user.getUserId()), user.getUserName(),
					user.getPicture(), FormatType.json);
		}
		user.setRongCloudToken(sdkHttpResult.getResult());
	}

	/**
	 * 用户登录
	 *
	 * @param userModel
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> login(@RequestBody RequestUserModel userModel, HttpServletRequest request) {
		try {
			if (ParameterUtils.validParams(userModel.getUserName(), userModel.getPassword())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if(StringUtil.isNotEmpty(request.getHeader("machineCode"))) {
				userModel.setUserMachineCode(request.getHeader("machineCode"));
			}
			ResponseUser user = userService.updateLogin(userModel);
			if(user == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20106), HttpStatus.OK);

			}
			String clientType = ClientType.APP;
			if(request.getHeader("phoneType") != null && request.getHeader("phoneType").length() > 0) {
				if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_IOS) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_ANDROID)){
					user.setUserMachineCode(request.getHeader("machineCode")==null?"":request.getHeader("machineCode"));
					clientType = ClientType.APP;
				} else if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_h5) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_WX)) {
					clientType = ClientType.H5;
				}
				
			}
			BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.APP_LOGIN_FLAG);
			if (baseRestrictions==null || baseRestrictions.getExperience()==1) {
				// 非店主不能登录小铺来了APP
				if ("APP".equals(clientType.toUpperCase())) {
					if(user.getRoleId() < 3){
						logger.info("小白用户 "+user.getUserId()+" 角色ID "+user.getRoleId()+" 于 "+DateUtils.getFullDate()+" 登录，被拒绝");
						return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20276), HttpStatus.OK);
					}
				}
			}
			ResponseEntity<?> responseEntity = checkUser(user,clientType);
			if (responseEntity != null) {
				return responseEntity;
			}
			setUserToken(user,clientType);
			if(user.getRoleId()<3){
				user.setTotalSale(0);
			}else{
				//user.setTotalSale(unifiedTreatmentService.userSalesAmountTotal(user.getUserId()));
				user.setTotalSale(0);
			}
			return new ResponseEntity<>(new ResponseResultModel<ResponseUser>(user), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("登录异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 用户退出登录
	 *
	 * @param userModel
	 * @return
	 */
	@RequestMapping(value = "/logOut", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> logOut(@RequestBody RequestUserModel userModel,HttpServletRequest request) {
		try {
			if (ParameterUtils.validParams(userModel.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			
			String clientType = ClientType.APP;
			if(request.getHeader("phoneType") != null && request.getHeader("phoneType").length() > 0) {
				if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_IOS) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_ANDROID)){
					clientType = ClientType.APP;
				} else if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_h5) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_WX)) {
					clientType = ClientType.H5;
				}
				
			}
			
			userService.logOut(userModel.getUserId(),clientType);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("退出登录异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 用户注册
	 *
	 * @param userModel
	 * @return
	 */
	@RequestMapping(value = "/register", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> register(@RequestBody RequestUserModel userModel, HttpServletRequest request) {
		try {
			if (ParameterUtils.validParams(userModel.getMobilePhone(), userModel.getPassword(), userModel.getCode())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}

			/**
			 * 判断用户是否已被注册
			 */
			int id = userService.selectUserIdByUserName(userModel.getMobilePhone());
			if (1 == id) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20108), HttpStatus.OK);
			}

			/**
			 * 校检验证码
			 */
			boolean re = smsService.checkVerifyCode(userModel.getMobilePhone(), SmsConstant.TYPE_REGISTER,
					userModel.getCode(), true);
			if (!re) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20109), HttpStatus.OK);
			}

			/*
			 * add by liujie 生成用户信息转移到下面的方法
			 */
			int res = registerByRequestParam(userModel, request);
			if (1 == res) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			} else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			}
		} catch (Exception e) {
			if (e.getMessage().equals("20002")) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			} else if (e.getMessage().equals("20004")) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20110), HttpStatus.OK);
			}
			logger.error("注册异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 根据手机号码查询用户是否存在
	 * 
	 * @param userModel
	 * @return
	 */
	@RequestMapping(value = "/getUserInfoByMobile", method = RequestMethod.GET)
	@IpAccessAnnotation(value = "")
	public ResponseEntity<?> getUserInfoByMobile(@RequestParam String mobile) {
		if (mobile == null || StringUtils.isEmpty(mobile)) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20115), HttpStatus.OK);
		}
		int userId = userService.selectUserIdByUserName(mobile);
		if (userId == 1) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} else {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
		}
	}

	/**
	 * 初始化用户信息 liujie
	 *
	 * @param requestModel
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/initUserInfo", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> initUserInfo(@RequestBody RequestUserModel requestModel) {
		try {
			Long userId = userService.queryUserId(requestModel);
			ResponsePersonalInfoset personalInfo = userService.selectUserPicture(userId);
			UserBasicInfo userBasicInfo = new UserBasicInfo();
			UserSwitchInfo switchInfo = new UserSwitchInfo();
			// 用户虚拟币信息
			// ResponseIntegralModel reIntegral =
			// integralRecordService.getIntegralNumber(userId);
			// 获取系统 签到 申请验证码验证的开关状态
			// int signinStatus = userService.selectSigninFlag();
			Integer apply_credit_status = smsService.getVoiceVerifyCodeStatus(CFlagEnum.apply_credit.getKey());
			// switchInfo.setSignInCoinfig(signinStatus);
			switchInfo.setVoicApplayCredit(apply_credit_status);

			userBasicInfo.personalInfo2BasicInfo(personalInfo);

			// assetInfo.IntegralModel2AssetInfo(reIntegral);
			UserInitResponse initInfo = new UserInitResponse();

			initInfo.setBasicInfo(userBasicInfo);
			initInfo.setSwitchInfo(switchInfo);

			return new ResponseEntity<>(new ResponseResultModel<>(initInfo), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("我的功能异常:", e);
			return new ResponseEntity<>(ResponseBaseModel.response20000(), HttpStatus.OK);
		}
	}

	/**
	 * 忘记密码
	 *
	 * @param userModel
	 * @return
	 */
	@RequestMapping(value = "/resetPassword", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> resetPassword(@RequestBody RequestUserModel userModel) {
		try {
			String mobile = userModel.getMobilePhone(), code = userModel.getCode();
			if (ParameterUtils.validParams(mobile, code, userModel.getPassword())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}

			ResponseUser user = null;
			if (smsService.checkVerifyCode(mobile, SmsConstant.TYPE_RESETPWD, code, true)) {
				user = userService.updatePassword(userModel);
			}

			if (null == user) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			} else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error("重置密码异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 修改密码
	 *
	 * @param userModel
	 * @return
	 */
	@RequestMapping(value = "/changePassword", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> changePassword(@RequestBody RequestUserModel userModel) {
		try {

			if (ParameterUtils.validParams(userModel.getUserName(), userModel.getPassword(), userModel.getNewPass())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}

			int res = userService.updatePasswordByChange(userModel);
			if (0 == res) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			} else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error("修改密码异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	private int registerByRequestParam(RequestUserModel userModel, HttpServletRequest request) throws Exception {
		String channelName = request.getHeader("channel");
		if (channelName != null && !channelName.isEmpty()) {
			channelName = channelName.toLowerCase();
			PromotionChannel channel = channelService.selectByName(channelName);
			if (channel == null)
				channel = channelService.saveChannel(channelName);
			userModel.setChannelId(channel.getId());
		}
		userModel.setUserIp(getRemoteAddress(request));

		return userService.saveRegister(userModel);
	}

	private String getRemoteAddress(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("Proxy-Client-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getHeader("WL-Proxy-Client-IP");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
			ip = request.getRemoteAddr();
		if (ip.matches(
				"^(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])\\.(\\d{1,2}|1\\d\\d|2[0-4]\\d|25[0-5])")) {
			return ip;
		}
		return "0.0.0.0";
	}

	// =====================modify by liujie
	// 20160503=================================//

	/**
	 * 用户添加反馈意见
	 * 
	 * @param requestUseradvice
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/saveAdvice", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> saveUserAdvice(@RequestBody RequestUserAdviceModel requestUseradvice) {
		try {
			userAdviceService.saveAdvice(requestUseradvice);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("添加用户反馈意见异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 修改用户个人设置
	 * 
	 * @param requsetPersonalInfo
	 * @return
	 */
	@RequestMapping(value = "/updatePersonalInfo", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> updatePersonalInfo(@RequestBody RequsetPersonalInfo requsetPersonalInfo) {
		try {

			if (!ParameterUtils.validParams(requsetPersonalInfo.getPicture())) {
				byte[] picture = Base64.decode(requsetPersonalInfo.getPicture());
				UploadObject aa = new UploadObject();
				Map<String, Object> imageMap = aa.uploadImage(picture, "200", "200");
				String imageUrl = ((ImageProperties) imageMap.get("imageProperties")).getImagePath();
				requsetPersonalInfo.setPicture(imageUrl);
			}

			boolean Personalinfo = userService.updateUserInfoset(requsetPersonalInfo);
			if (Personalinfo) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			} else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			}
		} catch (InvalidArgumentException iae) {
			logger.error("修改用户个人设置, 参数报错:", iae);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000, iae.getMessage()), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("修改用户个人设置:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 按条件修改用户设置
	 * 
	 * @param requestUserSet
	 * @return
	 */

	@ResponseBody
	@RequestMapping(value = "/updateUserSet", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> updateUserSet(@RequestBody RequestUserSetModel requestUserSet) {
		try {
			UserSet userset = new UserSet();
			userset.setUserId(requestUserSet.getUserId());
			userset.setDeviceId(requestUserSet.getDeviceId());
			userset.setAttentionSwitch(requestUserSet.getAttentionSwitch());
			userset.setMsgSwitch(requestUserSet.getMsgSwitch());
			userSetService.updateUserSet(userset);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("修改用户设置异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 查询个人中心主界面的接口
	 *
	 * @param requestUseradvice
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getPersonlMainInfo", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getMineInfo(@RequestBody RequestPersonIMainInfoModel requestUseradvice) {
		try {
			ResponseMineInfoModel mineInfo = userService.selectMineInfo(requestUseradvice.getUserId(),
					requestUseradvice.getNoticeClickDate());

			return new ResponseEntity<>(new ResponseResultModel<>(mineInfo), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询个人中心主界面的接口:", e);
			return new ResponseEntity<>(ResponseBaseModel.response20000(), HttpStatus.OK);
		}
	}

	/**
	 * {"userIp":"110.94.0.0","userId":"1"} ip定位接口
	 * 
	 * @param param
	 * @param request
	 * @return
	 * @throws PlatformException
	 */
	@RequestMapping(value = "/ipPosition", method = { RequestMethod.GET })
	@ResponseBody
	public ResponseEntity<?> ipPosition(HttpServletRequest request) throws BusinessException {
		String userStr = request.getParameter("userId");
		String ip = request.getParameter("userIp");
		long userId = StringUtils.isEmpty(userStr) ? 0 : Long.parseLong(userStr);
		String[] area = IPUtils.find(ip);
		userService.setUserLocated(userId, ip);
		String res = ip + ":" + area[0] + area[1] + area[2] + ":userId" + userId;
		return new ResponseEntity<>(new ResponseResultModel<String>(res), HttpStatus.OK);
	}

	/**
	 * 用户信息收集和百度chanelID更新 modify by liujie 2016-03-07 增加参数channalId,type
	 * 
	 * @param param
	 * @return
	 */
	@RequestMapping(value = "/userOtherInfoSet", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> userInfoCollect(@RequestBody RequestGuest param, HttpServletRequest request) {

		String channelName = request.getHeader("channel");
		// Base baseResult = new Base();
		ErrorEnum errorEnum = ErrorEnum.C10000;
		String guestId = param.getGuestId();
		String chanelId = param.getChannelId();
		String userStr = param.getUserId();
		String ip = getRemoteAddress(request);
		if (ParameterUtils.validParams(guestId)) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
		}
		long userId = StringUtils.isEmpty(userStr) ? 0 : Long.parseLong(userStr);
		Guest guest = guestService.selectByCode(guestId);

		if (guest == null) {
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20116), HttpStatus.OK);
		}

		/*
		 * 设备日活统计 add by liujie 2016-03-25
		 */
		int result = deviceActive(ip, userId, guestId, channelName);
		if (result == 0)
			logger.info("设备今日日活已统计...");
		if (StringUtils.isEmpty(userStr) && StringUtils.isEmpty(guestId)) {

		} else {
			try {
				if (userId <= 0) {
					if (guest != null) {
						// 若存在绑定关系，匿名用户直接替换成其绑定用户
						UserGuest ug = userService.getUserGuestByGuestId(guest.getId());
						if (ug != null)
							userId = ug.getUserId();
					}
				}
				// 用户定位
				if (userId == 0) {// 匿名用户
					userService.setGuestLocated(guest, ip);
				} else {// 正常用户
					userService.setUserLocated(userId, ip);
				}
			} catch (NumberFormatException | BusinessException e1) {
				logger.info("loctionUser error");
			}
		}

		try {
			if (!StringUtils.isEmpty(chanelId)) {
				if ("".equals(chanelId)) {
					errorEnum = ErrorEnum.C20117;
				} else {
					if (chanelId.length() == 19) {
						guest.setChannalId(chanelId);
						guest.setDeviceType(param.getType());
						errorEnum = ErrorEnum.C10000;
					} else {
						errorEnum = ErrorEnum.C20117;
					}
				}
				return new ResponseEntity<>(new ResponseBaseModel(errorEnum), HttpStatus.OK);
			} else {
				errorEnum = ErrorEnum.C29904;
				return new ResponseEntity<>(new ResponseBaseModel(errorEnum), HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error("更新设备信息异常:" + e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20118), HttpStatus.OK);
		} finally {
			// 更新设备信息
			guestService.updateInfo(guest);
		}
	}

	/**
	 * 判断是否新设备 add by liujie 2016-03-15
	 * 
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/isNewDevice", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> isNewDevice(@RequestBody RequestBaseModel model) {
		try {

			String guestId = model.getGuestId();
			if (ParameterUtils.validParams(guestId)) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29903), HttpStatus.OK);
			}

			int isNew = userService.isNewDevice(guestId) ? 1 : 0;
			return new ResponseEntity<>(new ResponseResultModel<Integer>(isNew), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("isNewDevice异常:", e, e.getMessage());
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * add by liujie 2016-03-16 判断手机运营商
	 */
	// private String validateMobile(String mobile) {
	// String returnString = "";
	// if (mobile == null || mobile.trim().length() != 11) {
	// return "-1"; // mobile参数为空或者手机号码长度不为11，错误！
	// }
	// if (mobile.trim().substring(0, 3).equals("134") ||
	// mobile.trim().substring(0, 3).equals("135")
	// || mobile.trim().substring(0, 3).equals("136") ||
	// mobile.trim().substring(0, 3).equals("137")
	// || mobile.trim().substring(0, 3).equals("138") ||
	// mobile.trim().substring(0, 3).equals("139")
	// || mobile.trim().substring(0, 3).equals("150") ||
	// mobile.trim().substring(0, 3).equals("151")
	// || mobile.trim().substring(0, 3).equals("152") ||
	// mobile.trim().substring(0, 3).equals("157")
	// || mobile.trim().substring(0, 3).equals("158") ||
	// mobile.trim().substring(0, 3).equals("159")
	// || mobile.trim().substring(0, 3).equals("178") ||
	// mobile.trim().substring(0, 3).equals("182")
	// || mobile.trim().substring(0, 3).equals("183") ||
	// mobile.trim().substring(0, 3).equals("184")
	// || mobile.trim().substring(0, 3).equals("187") ||
	// mobile.trim().substring(0, 3).equals("188")
	// || mobile.trim().substring(0, 3).equals("147")) {
	// returnString = "1"; // 中国移动
	// } else if (mobile.trim().substring(0, 3).equals("130") ||
	// mobile.trim().substring(0, 3).equals("131")
	// || mobile.trim().substring(0, 3).equals("132") ||
	// mobile.trim().substring(0, 3).equals("145")
	// || mobile.trim().substring(0, 3).equals("155") ||
	// mobile.trim().substring(0, 3).equals("156")
	// || mobile.trim().substring(0, 3).equals("185") ||
	// mobile.trim().substring(0, 3).equals("186")
	// || mobile.trim().substring(0, 3).equals("176")) {
	// returnString = "2"; // 中国联通
	// } else if (mobile.trim().substring(0, 3).equals("133") ||
	// mobile.trim().substring(0, 3).equals("153")
	// || mobile.trim().substring(0, 3).equals("177") ||
	// mobile.trim().substring(0, 3).equals("180")
	// || mobile.trim().substring(0, 3).equals("181") ||
	// mobile.trim().substring(0, 3).equals("189")) {
	// returnString = "3"; // 中国电信
	// } else {
	// returnString = "0"; // 未知运营商
	// }
	// return returnString;
	// }

	/**
	 * 查询用户的个人信息
	 *
	 * @param requestBaseModel
	 * @return
	 */
	@RequestMapping(value = "/queryPersonInfo", method = RequestMethod.POST)
	public ResponseEntity<?> queryPersonInfo(@RequestBody RequestBaseModel requestBaseModel) {
		try {
			ResponsePersonalInfoset personalinfo = userService.selectUserPicture(requestBaseModel.getUserId());
			if (personalinfo != null) {
				return new ResponseEntity<>(new ResponseResultModel<>(personalinfo), HttpStatus.OK);
			} else {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error("获取用户的个人信息异常", e);
			return new ResponseEntity<>(ResponseBaseModel.response20000(), HttpStatus.OK);
		}
	}

	/**
	 * 按条件查找用户设置
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getUserSet", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getUserSet(@RequestBody RequestUserSetModel requestUserSet) {
		try {
			UserSet userset = new UserSet();
			userset.setUserId(requestUserSet.getUserId());
			UserSet uSet = userSetService.selectUserSet(userset);
			return new ResponseEntity<>(new ResponseResultModel<UserSet>(uSet), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查看用户设置异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 设备是否绑定
	 * 
	 * @param userModel
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/isAssoicated", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> isAssoicated(@RequestBody RequestUserModel userModel) {
		try {
			if (ParameterUtils.validParams(userModel.getUserName(), userModel.getGuestId())) {
				logger.error("缺少必传参数:" + userModel);
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29903), HttpStatus.OK);
			}

			// 根据用户名获取当前用户ID
			ResponseUser user = userService.getUserByName(userModel.getUserName());
			if (user == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
			}
			// 获取当前guestId的用户ID,即gid
			Guest guest = guestService.selectByCode(userModel.getGuestId());
			if (guest == null) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20116), HttpStatus.OK);
			}
			Long uid = user.getUserId();
			Long gid = guest.getId();

			// 获取绑定数据
			UserGuest guser = userService.getUserGuestByGuestId(gid);
			if (guser != null && guser.getUserId().intValue() != uid) {// 被绑定用户不是当前用户、设备被占用
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20105), HttpStatus.OK);
			}

			logger.info("允许登录！");
			// 是当前绑定用户，可以登录
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);

		} catch (Exception e) {
			logger.error("isAssoicated异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}

	}

	/**
	 * 设备日活统计
	 * 
	 * @param ip
	 * @param userId
	 * @param channelName
	 * @return
	 * @throws PlatformException
	 */
	private int deviceActive(String ip, long userId, String guestId, String channel) {
		String located = userService.getCurrentCode(ip);
		return guestService.saveDeviceActiveLog(guestId, userId, located, ip, channel);
	}

	/**
	 * 根据用户id查询用户信息
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getUserEntityByIdNoPassword", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getUserEntityByIdNoPassword(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getUserId() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			User user = userService.getUserEntityByIdNoPassword(requestUserModel.getUserId());
			if (user == null) {
				// 此用户不存在
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			if (user.getLockStatus() == 1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20120), HttpStatus.OK);
			}
			if (user.getIsBlack() == 1) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20119), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseResultModel<User>(user), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询用户信息异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 注册用户
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/userRegistration", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> userRegistration(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getUserName() == null || requestUserModel.getPassword() == null
					|| requestUserModel.getCode() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			int regSource = requestUserModel.getRegSource();
			int i = userService.userRegistration(requestUserModel.getUserName(), requestUserModel.getPassword(),
					requestUserModel.getCode(), regSource);
			if (i == 2) {
				// 注册失败
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20101), HttpStatus.OK);
			}
			if (i == 3) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20109), HttpStatus.OK);
			}
			ResponseUser user = userService.getUserByName(requestUserModel.getUserName());
			return new ResponseEntity<>(new ResponseResultModel<ResponseUser>(user), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("注册用户异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 修改密码
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUserPasswordById", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> updateUserPasswordById(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getUserId() == null || requestUserModel.getPassword() == null|| requestUserModel.getNewPass() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			int i = userService.updateUserPasswordById(requestUserModel.getUserId(), requestUserModel.getPassword(),requestUserModel.getNewPass());
			if (i == 100) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C25007), HttpStatus.OK);
			}
			if(i == 200){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C25006), HttpStatus.OK);
			}
			if(i == 300){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C25008), HttpStatus.OK);
			}
			if(i ==1){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}
			if(requestUserModel.getUserId() != null && requestUserModel.getUserId() > 0)userService.updateUserCacheByUserId(requestUserModel.getUserId());
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("修改密码异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 忘记密码
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUserPasswordByUserName", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> updateUserPasswordByUserName(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getUserName() == null || requestUserModel.getNewPass() == null
					|| requestUserModel.getCode() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			int i = userService.updateUserPasswordByUserName(requestUserModel.getUserName(),
					requestUserModel.getNewPass(), requestUserModel.getCode());
			if (i == 0) {
				// 验证码不正确
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20109), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("忘记密码异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 退出登录
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUserLastLoginTime", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> updateUserLastLoginTime(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getUserId() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			int i = userService.updateUserLastLoginTime(requestUserModel.getUserId());
			if (i <= 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20122), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("忘记密码异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 我关注的达人
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectPictureAndNickName", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> selectPictureAndNickName(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getUserId() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			List<MyattentionTalent> MyattentionTalentList = userService.selectPictureAndNickName(
					requestUserModel.getUserId(), requestUserModel.getStartIndex(), requestUserModel.getPageSize());
			return new ResponseEntity<>(new ResponseResultModel<List<MyattentionTalent>>(MyattentionTalentList),
					HttpStatus.OK);
		} catch (Exception e) {
			logger.error("我关注的达人异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 我邀请的好友
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/selectUserByRecommendFrom", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> selectUserByRecommendFrom(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getRecommendFrom() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			List<MyattentionTalent> MyattentionTalentList = userService.selectUserByRecommendFrom(
					requestUserModel.getRecommendFrom(), requestUserModel.getStartIndex(),
					requestUserModel.getPageSize());
			return new ResponseEntity<>(new ResponseResultModel<List<MyattentionTalent>>(MyattentionTalentList),
					HttpStatus.OK);
		} catch (Exception e) {
			logger.error("我邀请的好友异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 我邀请的好友数量
	 * @param requestUserSet requestUserSet.recommendFrom 我的身份id（被邀请人的推荐人身份id）
	 */
	@ResponseBody
	@RequestMapping(value = "/selectUserByRecommendFromCount", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> selectUserByRecommendFromCount(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getRecommendFrom() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			} else {
				MyInvitationFriend myInvitationFriend = null;
				if ("".equals(requestUserModel.getRecommendFrom().trim())) {//无身份ID返回0
					myInvitationFriend = new MyInvitationFriend();
				} else {
					myInvitationFriend = userService.selectUserByRecommendFromCount(requestUserModel.getRecommendFrom());
				}
				return new ResponseEntity<>(new ResponseResultModel<MyInvitationFriend>(myInvitationFriend), HttpStatus.OK);
			}
		} catch (Exception e) {
			logger.error("我邀请的好友异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 修改昵称
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateNickName", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> updateNickName(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getNickName() == null || requestUserModel.getUserId() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			int i = userService.updateNickName(requestUserModel.getNickName(), requestUserModel.getUserId());
			if (i == 0) {
				// 修改失败
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20127), HttpStatus.OK);
			}
			userService.updateUserCacheByUserId(requestUserModel.getUserId());
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("修改昵称异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 修改头像
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUserPicture", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> updateUserPicture(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getPicture() == null || requestUserModel.getUserId() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			int i = userService.updateUserPicture(requestUserModel.getPicture(), requestUserModel.getUserId());
			if (i == 0) {
				// 修改失败
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20128), HttpStatus.OK);
			}
			userService.updateUserCacheByUserId(requestUserModel.getUserId());
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("修改头像异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 动态密码登录
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/dynamicRegister", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> dynamicRegister(@RequestBody RequestUserModel requestUserModel,HttpServletRequest request) {
		try {
			if (requestUserModel.getUserName() == null || requestUserModel.getCode() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			int i = checkCodeService.selectCheckCodeByMobile(requestUserModel.getUserName(),requestUserModel.getCode());
			if (i == 0) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20126), HttpStatus.OK);
			}
			ResponseUser user = userService.dynamicRegister(requestUserModel.getUserName());
			if (user == null) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			if(!StringUtil.isEmpty(user.getPassword())){
				user.setIsHasLoginPwd("yes");
				user.setPassword("");// 登录密码不返回给前段
			}else {
				user.setIsHasLoginPwd("no");
			}
			
			String clientType = ClientType.APP;
			if(request.getHeader("phoneType") != null && request.getHeader("phoneType").length() > 0) {
				if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_IOS) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_ANDROID)){
					user.setUserMachineCode(request.getHeader("machineCode")==null?"":request.getHeader("machineCode"));
					clientType = ClientType.APP;
				} else if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_h5) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_WX)) {
					clientType = ClientType.H5;
				}
				
			}
			BaseRestrictions baseRestrictions = baseRestrictionsService.getBaseRestrictionsForCache(BaseRestrictionsEnum.APP_LOGIN_FLAG);
			if (baseRestrictions==null || baseRestrictions.getExperience()==1) {
				// 非店主不能登录小铺来了APP
				if ("APP".equals(clientType.toUpperCase())) {
					if(user.getRoleId() < 3){
						logger.info("小白用户 "+user.getUserId()+" 角色ID "+user.getRoleId()+" 于 "+DateUtils.getFullDate()+" 登录，被拒绝");
						return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20276), HttpStatus.OK);
					}
				}
			}
			ResponseEntity<?> responseEntity = checkUser(user,clientType);
			if (responseEntity != null) {
				return responseEntity;
			}
			User _updateUser = new User();
			_updateUser.setId(user.getUserId());
			if(StringUtil.isNotEmpty(request.getHeader("machineCode"))) {
				_updateUser.setUserMachineCode(request.getHeader("machineCode"));
			}
			userService.updateUserLoginInfo(_updateUser);
			
			
			
			
			setUserToken(user,clientType);

			return new ResponseEntity<>(new ResponseResultModel<ResponseUser>(user), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("动态密码登录异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 推荐用户注册
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/recommendUserRegister", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> recommendUserRegister(@RequestBody RequestUserModel requestUserModel,HttpServletRequest request) {
		return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C99996), HttpStatus.OK);
		/*try {
			if (requestUserModel.getUserName() == null || requestUserModel.getCode() == null
					|| requestUserModel.getRecommendFrom() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			
			String clientType = ClientType.APP;
			if(request.getHeader("phoneType") != null && request.getHeader("phoneType").length() > 0) {
				if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_IOS) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_ANDROID)){
					clientType = ClientType.APP;
				} else if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_h5) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_WX)) {
					clientType = ClientType.H5;
				}
				
			}
			
			return userService.updaterecommendUserRegister(requestUserModel.getUserName(), requestUserModel.getCode(),
					requestUserModel.getRecommendFrom(), requestUserModel.getNickName(), requestUserModel.getPicture(),
					requestUserModel.getSex(),clientType);
		} catch (Exception e) {
			logger.error("推荐用户注册异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}*/
	}

	/**
	 * 美妆咨询界面获取所有讲师并按粉丝数由多到少排序
	 * 
	 * @author 卫耀华
	 * @return
	 */
	@RequestMapping(value = "/meiZhuangZiXun", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> meiZhuangZiXun(@RequestBody RequestUserModel requestUser) {
		try {
			List<ResponseUserVo> list = userService.selectUserByRoleId7NoPassword(requestUser.getStartIndex(),
					requestUser.getPageSize());
			int count = userService.countUserByRoleId7();
			ResponseUserPage pageModel = new ResponseUserPage(count, list);
			return new ResponseEntity<>(new ResponseResultModel<ResponsePageModel<ResponseUserVo>>(pageModel),
					HttpStatus.OK);
		} catch (Exception e) {
			logger.error("系统异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 上传头像（Base64位）
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@RequestMapping(value = "/imgBasePath", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> imgBasePath(@RequestBody ImgBasePathRequest request) {
		try {
			if (ParameterUtils.validParams(request.getImgBase())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			if (ParameterUtils.validParams(request.getSuffix())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			byte[] b = Base64.decode(request.getImgBase());
			String imgurl = QiniuUtils.uploadByBytys64("file/user/", b, request.getSuffix());
			if ("".equals(imgurl)) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29907), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseResultModel<String>(imgurl), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("上传图片异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 编辑达人主页
	 * 
	 * @author 卫耀华
	 * @date 2016-10-25
	 * @param requestUser
	 * @return
	 */
	@RequestMapping(value = "/editTalentHomePage", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> editTalentHomePage(@RequestBody RequestUserModel requestUser) {
		try {
			if (ParameterUtils.validParams(requestUser.getTalentId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			User talentUser = userService.getUser(requestUser.getTalentId());
			if (null == talentUser) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			int updates = userService.updateUserJianjieAndBackgroundImageById(requestUser.getTalentId(),
					requestUser.getSynopsis(), requestUser.getBackgroundImage());
			if (updates <= 0) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C29908), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("编辑达人主页异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 获取我的可用妆币
	 * 
	 * @author 卫耀华
	 * @param requestUser
	 * @return
	 */
	@RequestMapping(value = "/getMoneyByUserId", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getMoneyByUserId(@RequestBody RequestUserModel requestUser) {
		try {
			if (ParameterUtils.validParams(requestUser.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			User user = userService.getUser(requestUser.getUserId());
			if (null == user) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			Map<String, Integer> map = new HashMap<String, Integer>();
			map.put("money", user.getMoney());
			return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("编辑达人主页异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 查询用户累计销售额度和会员价格
	 * 
	 * @author
	 * @param requestUser
	 * @return
	 */
	@RequestMapping(value = "/selectMemberFeeAndTotalSale", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> selectMemberFeeAndTotalSale(@RequestBody RequestUserModel requestUser) {
		try {
			if (ParameterUtils.validParams(requestUser.getUserId())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			MemberFeeAndTotalSale memberFeeAndTotalSale = userService
					.selectMemberFeeAndTotalSale(requestUser.getUserId());
			if (null == memberFeeAndTotalSale) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20111), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseResultModel<MemberFeeAndTotalSale>(memberFeeAndTotalSale),
					HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询用户累计销售额度和会员价格异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

//	/**
//	 * 清空用户表数据
//	 */
//	// @Scheduled(cron = "*/5 * * * * ? ")//每五秒钟触发一次
//	@Scheduled(cron = "0 0 0 * * ?") // 每天晚上12点触发一次
//	public void cancelTalentQualification() {
//		List<User> userList = userService.selectUserWhereUserNameIsNull();
//		userService.cancelTalentQualification(userList);
//	}

	/**
	 * 是否打开推荐
	 * 
	 * @author
	 * @param requestUser
	 * @return
	 */
	@RequestMapping(value = "/updateisOpenRecommandById", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> updateisOpenRecommandById(@RequestBody RequestUserModel requestUser) {
		try {
			if (ParameterUtils.validParams(requestUser.getUserId(), requestUser.getIsOpenRecommand())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			userService.updateisOpenRecommandById(requestUser.getIsOpenRecommand(), requestUser.getUserId());
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("打开推荐页面异常", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 网页推荐用户注册
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/webpageRegister", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> webpageRegister(@RequestBody RequestUserModel requestUserModel,HttpServletRequest request) {
		try {
			if (requestUserModel.getUserName() == null || requestUserModel.getCode() == null
					|| requestUserModel.getRecommendFrom() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			
			String clientType = ClientType.APP;
			if(request.getHeader("phoneType") != null && request.getHeader("phoneType").length() > 0) {
				if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_IOS) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_ANDROID)){
					clientType = ClientType.APP;
				} else if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_h5) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_WX)) {
					clientType = ClientType.H5;
				}
				
			}
			
			return userService.webpageRegister(requestUserModel.getUserName(), requestUserModel.getCode(),
					requestUserModel.getRecommendFrom(),clientType);
		} catch (Exception e) {
			logger.error("网页推荐用户注册异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/**
	 * 讲师店铺讲师基本信息
	 * 
	 * @author 卫耀华
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/userBaseInfo", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> userBaseInfo(@RequestBody RequestUserModel request) {
		try {
			if (request.getUserId() == 0) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			User user = userService.getUser(request.getUserId());
			if (user == null) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("userId", user.getId());
			map.put("nickName", user.getNickName());// 昵称
			map.put("picture", user.getPicture());// 头像
			map.put("fansCount", user.getFansCount());// 粉丝数
			map.put("backgroundImage", user.getBackgroundImage());// 达人主页背景图
			map.put("money", user.getMoney());
			map.put("commisionLimit", baseRestrictionsService.selectCommisionLimit());// 佣金满多少可提现
			return new ResponseEntity<>(new ResponseResultModel<>(map), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("讲师基本信息异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * 讲师信息
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/searchTeacher", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> searchTeacher(@RequestBody RequestUserModel model) {
		try {
			if (ParameterUtils.validParams(model.getPageNum(),model.getPageSize(),model.getSearchText())) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			List<ResponseTeacher> resModel = userService.searchTeacher(model.getStartIndex(),model.getPageSize(),model.getSearchText());
			return new ResponseEntity<>(new ResponseResultModel<>(resModel), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("讲师搜索异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	
	/**
	 * 查询用户头上的讲师异常啦
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getUserTeacherInfo", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getUserTeacherInfo(@RequestBody RequestUserModel model) {
		try {
			if (ParameterUtils.validParams(model.getUserId())) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
			}
			return userService.getUserTeacherInfo(model.getUserId());
		} catch (Exception e) {
			logger.error("查询用户头上的讲师异常啦:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * 修改用户支付密码
	 * 
	 * @param requestUserSet
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/updateUserPayPasswordById", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> updateUserPayPasswordById(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getUserId() == null || requestUserModel.getPayPwd()== null|| requestUserModel.getNewPayPwd() == null) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			//根据用户id 新旧密码      修改用户支付密码
			int i = userPayInfoService.updatePayPasswordById(requestUserModel.getUserId(),requestUserModel.getPayPwd(),requestUserModel.getNewPayPwd());
			if (i == 100) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C25007), HttpStatus.OK);
			}
			if(i == 200){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C25005), HttpStatus.OK);
			}
			if(i == 300){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C25008), HttpStatus.OK);
			}
			if(i == 1){
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
			}
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
			
		} catch (Exception e) {
			logger.error("修改支付密码异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	/**
	 * 
	* **********************************************
	* @Title: getUserInfoByIdNoPassword 
	* @Description: TODO(个人信息<新版>) 
	* @param @param requestUserModel
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年8月17日 下午4:24:02 
	* **********************************************
	 */
	@ResponseBody
	@RequestMapping(value = "/getUserInfoByIdNoPassword", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> getUserInfoByIdNoPassword(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getUserId() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			User user = this.userService.getUserEntityByIdNoPassword(requestUserModel.getUserId());
			if (user == null) {// 此用户不存在
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20113), HttpStatus.OK);
			}
			if (user.getLockStatus() == 1) {// 用户被锁定
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20120), HttpStatus.OK);
			}
			if (user.getIsBlack() == 1) {// 用户被拉黑
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20119), HttpStatus.OK);
			}
			ResponseNewUserModel pnum = new ResponseNewUserModel(user);
			pnum.setIsShowPayPwd(user.getRoleId()>=3?"yes":"no");
			pnum.setIsHasPayPwd(this.userPayInfoService.queryUserPayInfoByUserId(requestUserModel.getUserId()+"")==null?"no":"yes");
			pnum.setIsHasLoginPwd(user.getPassword()==null?"no":"yes");
			return new ResponseEntity<>(new ResponseResultModel<ResponseNewUserModel>(pnum), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询用户信息异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	
	
	
	@ResponseBody
	@RequestMapping(value = "/update_user_cache", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> update_user_cache(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getUserId() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			userService.updateUserCacheByUserId(requestUserModel.getUserId());
			return new ResponseEntity<>(new ResponseResultModel<ResponseNewUserModel>(null), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询用户信息异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/batch_update_user_cache")
	public ResponseEntity<?> batch_update_user_cache(Integer hour) {
		//对N小时内有过更新的用户进行批量缓存
		try {
			if (hour == null && hour > 0) {
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			//当前时间减N小时
			String endUpdateTime = DateUtil.longToString(DateUtil.addHour(-hour));
			List<User> _list = userService.selectUserByUpdateTime(endUpdateTime);
			for(User u : _list) {
				userService.updateUserCacheByUserId(u.getId());
				//下面这条在后期可以去掉，因为身份对象关系,在注册后确定下来，后面永远不会发生改变
				//userService.cacheUserPersionByUserId(u.getId());
			}
			return new ResponseEntity<>(new ResponseResultModel<ResponseNewUserModel>(null), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询用户信息异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
	
	
	@ResponseBody
	@RequestMapping(value = "/cache_role")
	public ResponseEntity<?> cache_role(Integer hour) {
		//对N小时内有过更新的用户进行批量缓存
		try {
			userService.cacheUserRoleInfo();
			return new ResponseEntity<>(new ResponseResultModel<ResponseNewUserModel>(null), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询用户信息异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	} 

	/**
	* 身份验证请求次数
	* @author gaoweiqi
	* @date 2017年8月19日 12:44:05
	*
	**/
	@ResponseBody
	@RequestMapping(value = "/idcardTime")
	public ResponseEntity<?> idcard(@RequestBody RequestUserModel requestUserModel) {
		try {
			if (requestUserModel.getUserId() == null) {
				// 必传参数未传
				return new ResponseEntity<ResponseBaseModel>(new ResponseBaseModel(ErrorEnum.C29901), HttpStatus.OK);
			}
			ResponseNewUserModel pnum = new ResponseNewUserModel(requestUserModel.getUserId(), userIdCardService.IdcardTimes(requestUserModel.getUserId()));
			return new ResponseEntity<>(new ResponseResultModel<ResponseNewUserModel>(pnum), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("查询用户信息异常:", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
}
